#include "DialogVideoSetup.h"
#include "ui_DialogVideoSetup.h"

#include <QMessageBox>

DialogVideoSetup::DialogVideoSetup(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::DialogVideoSetup)
{
    ui->setupUi(this);

    ui->btnOpticalMinus->setAutoRepeat(true);
    ui->btnOpticalMinus->setAutoRepeatDelay(autoRepeatDelay);
    ui->btnOpticalMinus->setAutoRepeatInterval(autoRepeatInterval);
    ui->btnOpticalPlus->setAutoRepeat(true);
    ui->btnOpticalPlus->setAutoRepeatDelay(autoRepeatDelay);
    ui->btnOpticalPlus->setAutoRepeatInterval(autoRepeatInterval);

    ui->btnDigitalMinus->setAutoRepeat(true);
    ui->btnDigitalMinus->setAutoRepeatDelay(autoRepeatDelay);
    ui->btnDigitalMinus->setAutoRepeatInterval(autoRepeatInterval);
    ui->btnDigitalPlus->setAutoRepeat(true);
    ui->btnDigitalPlus->setAutoRepeatDelay(autoRepeatDelay);
    ui->btnDigitalPlus->setAutoRepeatInterval(autoRepeatInterval);

    ui->btnWinMinus->setAutoRepeat(true);
    ui->btnWinMinus->setAutoRepeatDelay(autoRepeatDelay);
    ui->btnWinMinus->setAutoRepeatInterval(autoRepeatInterval);
    ui->btnWinPlus->setAutoRepeat(true);
    ui->btnWinPlus->setAutoRepeatDelay(autoRepeatDelay);
    ui->btnWinPlus->setAutoRepeatInterval(autoRepeatInterval);
}
void DialogVideoSetup::setCamera(WidgetVideo( *widgetVideo), QWidget *wtVideo)
{

    this->widgetVideo = widgetVideo;
    this->wtVideo = wtVideo;
    ui->leX->setText(QString::asprintf("%d",wtVideo->x()));
    ui->leY->setText(QString::asprintf("%d",wtVideo->y()));
    ui->leW->setText(QString::asprintf("%d",wtVideo->width()));
    ui->leH->setText(QString::asprintf("%d",wtVideo->height()));
    ui->lblWinSize->setText(QString::asprintf("%dx%d", wtVideo->width(), wtVideo->height()));

    this->camera = widgetVideo->camera;

    connect(camera, QOverload<QCamera::Error>::of(&QCamera::error), this, [=](QCamera::Error value) {
        qDebug() << "camera error:" << value;

        ui->teMsg->append(QString::asprintf("摄像头错误:%d", value));
    });

    connect(camera, &QCamera::statusChanged, [=](QCamera::Status status)
    {
        qDebug() << "cameraStatus=" << status;
        ui->teMsg->append(QString::asprintf("摄像头状态:%d", status));

        if (status == QCamera::ActiveStatus)
        {
            initCamera();
        }
    });

    if (this->camera->status() != QCamera::ActiveStatus)
    {
//        if (QMessageBox::question(this, "提示", "打开摄像头吗？") != QMessageBox::Yes)
//        {
//            return;
//        }

        ui->teMsg->append("正在打开摄像头......");

        QTimer::singleShot(1000, [=]{
            this->camera->start();
        });
    }
    else
    {
        initCamera();
    }
}

void DialogVideoSetup::initCamera()
{
    if (isFirstEntry)
    {
        focus = camera->focus();
        connect(focus, QOverload<qreal>::of(&QCameraFocus::opticalZoomChanged), [=](qreal value){
            ui->lblOptical->setText(QString::asprintf("%.1f", value));
        });
        connect(focus, QOverload<qreal>::of(&QCameraFocus::digitalZoomChanged), [=](qreal value){
            ui->lblDigital->setText(QString::asprintf("%.1f", value));
        });

        this->getCameraList();
        this->getCameraInfo();

        isFirstEntry = false;
    }
}
DialogVideoSetup::~DialogVideoSetup()
{
    delete ui;

    camera->disconnect();
}

void DialogVideoSetup::getCameraList()
{
    cameras = QCameraInfo::availableCameras();

    ui->cbCameraList->clear();

    qDebug() << "============================================================================";
    qDebug() << "getCameraList:";
    for (int i = 0; i < cameras.size(); i++)
    {
        qDebug() << "deviceName=" << cameras.at(i).deviceName(); //获取设备名称
        qDebug() << "description=" << cameras.at(i).description();
        qDebug() << "position=" << cameras.at(i).position();
        qDebug();

        ui->cbCameraList->addItem(cameras.at(i).description(), cameras.at(i).deviceName());
    }
    qDebug() << "============================================================================";

}

void DialogVideoSetup::getCameraInfo()
{
    //获取摄像头支持的分辨率、帧率等参数
    viewSets = camera->supportedViewfinderSettings();

    qDebug() << "============================================================================";
    qDebug() << "getCameraInfo length=" << viewSets.length();

    ui->cbCameraInfo->clear();
    int i = 0;
    QSize size;
    QString item;
    foreach (QCameraViewfinderSettings viewSet, viewSets)
    {
        size = viewSet.resolution();
        qDebug() << i
                 << "maximumFrameRate=" << viewSet.maximumFrameRate()
                 << "minimumFrameRate="<< viewSet.minimumFrameRate()
                 << "resolution="<< size
                 << "pixelFormat=" << viewSet.pixelFormat()
                 << "pixelAspectRatio=" << viewSet.pixelAspectRatio();
        qDebug();

        item = QString::asprintf("分辨率:%dx%d,最小帧率:%.0f,最大帧率:%.0f,格式:%d", size.width(), size.height(),
                                 viewSet.maximumFrameRate(),
                                 viewSet.minimumFrameRate(),
                                 viewSet.pixelFormat()
                                 );
        ui->cbCameraInfo->addItem(item, i++);
    }
    qDebug() << "============================================================================";


    opticalMax = focus->maximumOpticalZoom();
    digitalMax = focus->maximumDigitalZoom();
    ui->lblOpticalMax->setText(QString::asprintf("%.1f",opticalMax));
    ui->lblDigitalMax->setText(QString::asprintf("%.1f",digitalMax));

    optical = focus->opticalZoom();
    digital = focus->digitalZoom();
    ui->lblOptical->setText(QString::asprintf("%.1f", optical));
    ui->lblDigital->setText(QString::asprintf("%.1f", digital));

}


void DialogVideoSetup::on_cbCameraInfo_currentIndexChanged(int index)
{
    if (!isFirstEntry && index >= 0)
    {
        //设置摄像头参数
        camera->setViewfinderSettings(viewSets[index]);

        if (ui->cbWin->isChecked())
        {
            QSize size = viewSets[index].resolution();

            this->setWidgetVideoGeometry(size.width(), size.height());
        }

    }
}

void DialogVideoSetup::on_btnOpticalMinus_clicked()
{
    if (fabs(opticalMax - 1.0) < 0.001)
    {
        QMessageBox::warning(this, "警告", "该摄像头不支持物理缩放功能！");
        return;
    }

    optical -= ui->leOpticalStep->text().toDouble();

    if (optical < 1.0)
        optical = 1.0;

    focus->zoomTo(optical, digital);
}

void DialogVideoSetup::on_btnOpticalPlus_clicked()
{
    if (fabs(opticalMax - 1.0) < 0.001)
    {
        QMessageBox::warning(this, "警告", "该摄像头不支持物理缩放功能！");
        return;
    }
    optical += ui->leOpticalStep->text().toDouble();

    if (optical > opticalMax)
        optical = opticalMax;

    focus->zoomTo(optical, digital);
}

void DialogVideoSetup::on_btnDigitalMinus_clicked()
{
    if (fabs(digitalMax - 1.0) < 0.001)
    {
        QMessageBox::warning(this, "警告", "该摄像头不支持数字缩放功能！");
        return;
    }
    digital -= ui->leDigitalStep->text().toDouble();

    if (digital < 1.0)
        digital = 1.0;

    focus->zoomTo(optical, digital);
}

void DialogVideoSetup::on_btnDigitalPlus_clicked()
{
    if (fabs(digitalMax - 1.0) < 0.001)
    {
        QMessageBox::warning(this, "警告", "该摄像头不支持数字缩放功能！");
        return;
    }
    digital += ui->leDigitalStep->text().toDouble();

    if (digital > digitalMax)
        digital = digitalMax;

    focus->zoomTo(optical, digital);
}

void DialogVideoSetup::on_btnWinMinus_clicked()
{
    int w = wtVideo->width() - ui->leWinStep->text().toInt();
    if (w < MIN_WIDTH)
        w = MIN_WIDTH;

    int h = w * 0.5625;

    setWidgetVideoGeometry(w, h);
}

void DialogVideoSetup::setWidgetVideoGeometry(int w, int h)
{
    ui->leW->setText(QString::asprintf("%d", w));
    ui->leH->setText(QString::asprintf("%d", h));
    ui->lblWinSize->setText(QString::asprintf("%dx%d", w, h));

    wtVideo->setGeometry(ui->leX->text().toInt(), ui->leY->text().toInt(), w, h);
}

void DialogVideoSetup::on_btnWinPlus_clicked()
{
    int w = wtVideo->width() + ui->leWinStep->text().toInt();
    if (w > MAX_WIDTH)
        w = MAX_WIDTH;

    int h = w * 0.5625;

    setWidgetVideoGeometry(w, h);
}

void DialogVideoSetup::on_cbCameraList_currentIndexChanged(int index)
{
    if (!isFirstEntry && index>=0)
    {
        camera->stop();
        delete camera;

        camera = new QCamera(cameras[index]);
        widgetVideo->initCamera(camera);
    }
}
